import os, re

path = r'C:\Users\hufei\Desktop\Desktop'


def chinse2pinyin(ch_str):
    from pypinyin import pinyin
    from pypinyin.constants import Style
    return '_'.join([i[0] for i in pinyin(ch_str, style=Style.TONE3)])


def handle_space(_str: str):
    return _str.replace(' ', '')


def handle_kuo(_str: str):
    return _str.replace('（', '').replace('）', '').replace('(', '').replace(')', '').replace('-', '_').replace('+', '_')


def handle_num(_str: str):
    import re, random
    if re.match('^\d$', _str[0]):
        return random.choice(['a', 'b', 'c', 'd', 'e', 'f', 'x', 'z']) + _str
    return _str


def handle_all(_str):
    _str = chinse2pinyin(_str)
    _str = handle_space(_str)
    _str = handle_kuo(_str)
    _str = handle_num(_str)
    return _str


def rename_all_dir():
    for root, dirs, files in os.walk(path):
        for i in files:
            p1 = os.path.join(root, i)
            i2 = handle_all(i)
            t = os.path.splitext(i2)[0]
            if not re.match(r'^[a-zA-Z0-9_]+$', t):
                print(p1)
                continue
            p = os.path.join(root, i2)
            os.rename(p1, p)


def image2base64(image_path, outname):
    """

    :param image_path: 图片路径
    :type image_path: str
    :return:
    :rtype:
    """
    import os, base64, json
    _all_data = {}
    print(f'\033[92m{2} success \033[0m')
    for root, dirs, files in os.walk(image_path):
        for f in files:
            _file = os.path.join(root, f)
            _, filename = os.path.split(_file)
            filename_nofix, _ = os.path.splitext(filename)
            _, pofix = os.path.splitext(_file)
            if pofix.lower() in ('.png', '.jpg', '.jpeg', '.gif', '.svg'):
                with open(_file, "rb") as f:
                    base64_data = str(base64.b64encode(f.read()), encoding='utf-8')
                print(f'\033[92m{_file} success \033[0m')
                _all_data[filename_nofix] = (base64_data, pofix.upper().strip('.'))
    dt_s = json.dumps(_all_data)
    with open(f'{outname}.py', 'w') as f:
        f.write(f'image_dict={dt_s}')


def gen_image_file():
    for i in os.listdir(path):
        p = os.path.join(path, i)
        image2base64(p, i)


def gen_import(name: str):
    temp = """from huza.icons.images.{{name}} import image_dict as {{name}}_dict
class {{name2}}IconHandler(IconHandler):
    def __init__(self):
        super({{name2}}IconHandler, self).__init__()
        self._icon_database = {{name}}_dict"""

    from jinja2 import Environment
    env = Environment()
    paras = {'name': name, 'name2': name.capitalize()}
    tempate_obj = env.from_string(temp)
    fileStr = tempate_obj.render(**paras)

    print(fileStr)


def gen_import2(name: str):
    temp2 = """'{{name}}': {{name2}}IconHandler(),"""
    from jinja2 import Environment
    env = Environment()
    paras = {'name': name, 'name2': name.capitalize()}
    tempate_obj = env.from_string(temp2)
    fileStr = tempate_obj.render(**paras)

    print(fileStr)


if __name__ == '__main__':
    rename_all_dir()
    gen_image_file()
    for i in os.listdir(path):
        gen_import(i)
    for i in os.listdir(path):
        gen_import2(i)
